package com.db.server;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;

public class Server {
	private static List<ClientThread> listClient = new LinkedList<ClientThread>();
	private static Map<String, String> map = new HashMap<String, String>();
	private final static Logger logger = Logger.getLogger(Server.class.getName());
	public static void main(String[] args) throws IOException, InterruptedException {
		updateMap(args[0], true);
		ServerSocket socket = new ServerSocket(90);
		int counter = 0;
		while(true) {
		    Socket clientSocket = socket.accept();
		    logger.info("Client accepted");
		    counter++;
		    ClientThread clientThread = new ClientThread(map, clientSocket, counter);
		    listClient.add(clientThread);
		    clientThread.start();
		}
	}
	/**
	 * 
	 * Should be called by JMX, for example
	 * 
	 */
	
	public static void updateMap(String fileName, boolean flag) throws IOException {
		BufferedReader fileInput = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
		map.clear();
		String readString = fileInput.readLine();
		String[] readArray;
		while (readString != null) {
			readArray = readString.split(" ");
			map.put(readArray[0], readArray[1]);
			readString = fileInput.readLine();
		}
		fileInput.close();
		if (!(flag)) {
			Iterator<ClientThread> iterClient = listClient.iterator();
			while (iterClient.hasNext()) {
				iterClient.next().setMap(map);
			}
		}
	}

}
